package com.example.demo.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Controller   // 让Spring 框架启动时加载
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/login")
    @ResponseBody
    public HashMap<String,Object> login(String username, String password){
        HashMap<String,Object> res = new HashMap<>();
        int succ = 200;
        if(username!=null && password!=null &&
                username.equals("admin") && password.equals("admin")){
            res.put("msg","登录成功");
        }else{
            res.put("msg","登录失败");
        }
        res.put("succ",succ);
        return res;
    }



    @RequestMapping("/sum")
    public String sum(Integer num1,Integer num2){
        Integer sum = num1+num2;
        return String.format("<h1>计算的结果是：" +
                "%d</h1><a href='javascript:history.go(-1);'>返回</a>",num1+num2);
    }

    @RequestMapping("/m8")
    public HashMap<String, String> method_8() {
        HashMap<String, String> map = new HashMap<>();
        map.put("Java", "Java Value");
        map.put("MySQL", "MySQL Value");
        map.put("Redis", "Redis Value");
        return map;
    }

    @RequestMapping("/param10")
    public String param10(HttpServletResponse response, HttpServletRequest request){
        String name = request.getParameter("name");
        // 获取所有cookie信息
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies);
        return name+"你好";
    }


    @RequestMapping("/param1")
    public String param1(){
        return "目前能够正常接受到信息Param1";
    }

    @RequestMapping("/param9")
    public String param9(String name, @RequestPart("myfile") MultipartFile file) throws IOException {
        // 获取⽂件后缀名
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // ⽂件保存地址
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() +
                "/" + UUID.randomUUID() + fileName;
        // 保存⽂件
        file.transferTo(new File(filePath));
        return filePath + " 上传成功.";
    }

}
